package com.hmdp.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        String key = CACHE_SHOP_KEY + "typeList";
        //1.先从缓存中获取店铺类型数据
        String cacheTypeList = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(cacheTypeList)) {
            return Result.ok(JSON.parseArray(cacheTypeList, ShopType.class));
        }
        //2.若缓存不存在数据，则从数据库中获取并同步到缓存中
        List<ShopType> typeList = this.query().orderByAsc("sort").list();
        if (typeList == null){
            return Result.fail("获取店铺类型失败!");
        }
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(typeList),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(typeList);
    }
}
